package cn.org.donald.framework.config;

import cn.org.donald.framework.property.TableProperties;
import cn.org.donald.framework.pojo.entity.Table;
import cn.org.donald.mapper.TableMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 定时删除逻辑删除超过指定天数的记录
 * @author : Donald
 * @since : 2020/11/13 10:24
 */
@Component
public class ScheduleTask {

    private Logger logger = LoggerFactory.getLogger(ScheduleTask.class);

    @Autowired
    private TableMapper tableMapper;

    @Autowired
    private TableProperties tableProperties;

    @Scheduled(cron = "0 01 16 * * ?")
    public void executeDeleteTable(){
        logger.info("ScheduleTask execute: executeDeleteTable; execute time: {}",System.currentTimeMillis());

        List<Table> tables = tableMapper.selectTableName();
        int sum = tables.stream().mapToInt(table -> {
            if (!StringUtils.isEmpty(tableProperties.getExceptTable()) && tableProperties.getExceptTable().contains(table.getTableName())){
                return 0;
            }
            int i = tableMapper.deletePhysical(table.getTableName(),tableProperties.getDay());
            if (i > 0) {
                logger.info("executeDeleteTable: delete from: {}; deleted {} rows", table.getTableName(), i);
            }
            return i;
        }).sum();
        logger.info("total delete: {}", sum);
    }
}
